package com.maxd.controller.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.JdException;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.modules.coupon.service.CouponOrderDetailService;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.jifen.JiFenJpaRepository;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.pdd.PddJpaRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.cash.ICashService;
import com.maxd.service.message.IMessageService;
import com.maxd.service.userinfo.UserServiceImpl;
import com.maxd.service.wx.AccountService;
import com.maxd.service.wx.AccountTokenService;
import com.maxd.utils.*;
import com.maxd.utils.Base64;
import com.pdd.pop.sdk.common.util.JsonUtil;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.PopHttpClient;
import com.pdd.pop.sdk.http.api.pop.request.PddDdkOrderListIncrementGetRequest;
import com.pdd.pop.sdk.http.api.pop.response.PddDdkOrderListIncrementGetResponse;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.TbkOrderDetailsGetRequest;
import com.taobao.api.response.TbkOrderDetailsGetResponse;
import jd.union.open.order.query.request.OrderReq;
import jd.union.open.order.query.request.UnionOpenOrderQueryRequest;
import jd.union.open.order.query.response.OrderResp;
import jd.union.open.order.query.response.SkuInfo;
import jd.union.open.order.query.response.UnionOpenOrderQueryResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author maxd
 * 以下模块是 自动获取微信token和定时获取淘宝订单
 */
@Slf4j
@Component
public class OrderTask {
    private Logger logger = LoggerFactory.getLogger(OrderTask.class);
    /**
     * 定义 AccountTokenService
     */
    private final AccountTokenService accountTokenService;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private PddJpaRepository pddJpaRepository;
    @Autowired
    private ICashService iCashService;
    @Autowired
    private JiFenJpaRepository jiFenRepository;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    private IMessageService iMessageService;
    @Autowired
    private CouponOrderDetailService couponOrderDetailService;

    private SimpleDateFormat sdf;
    ExecutorService service = Executors.newFixedThreadPool(15);

    /**
     * 构造方法
     *
     * @param accountTokenService AccountTokenService
     */
    @Autowired
    public OrderTask(AccountTokenService accountTokenService) {
        this.accountTokenService = accountTokenService;
    }

    /**
     * 获取京东全部订单2分钟执行一次
     */
    @Scheduled(fixedDelay = 2 * 60 * 1000)
    void synOnceJDOrderOneMinus() {
        service.execute(() -> {
            logger.error("synOnceJDOrderOneMinus");
            getJdOrder();
        });
    }

    /**
     * 获取美团全部订单5分钟执行一次
     */
    @Scheduled(fixedDelay = 5 * 60 * 1000)
    void synOnceMTOrderOneMinus() {
        service.execute(() -> {
            getMTOrder();
        });
    }

    /**
     * 获取pdd订单 2分30执行一次
     */
    @Scheduled(fixedDelay = 150 * 1000)
    void synOncePddOrderOneMinus() {
        service.execute(() -> {
            logger.error("synOnceTaoBaoKeOrderThreeMinus");
            updatePddOrder();
        });
    }


    /**
     * 获取多麦订单 2分执行一次
     */
    @Scheduled(fixedDelay = 120 * 1000)
    void synOnceDuoMaiOrder() {
        service.execute(() -> {
            logger.error("synOnceDuoMaiOrder");
            service.execute(this::updateDuoMaiOrder);
            service.execute(this::updateJTKOrder);
            service.execute(this::updateDouYinOrder);
            service.execute(this::updateWphOrder);
        });
    }


    /**
     * 获取淘宝结算和付款订单 3分钟执行一次
     */
    @Scheduled(fixedDelay = 3 * 60 * 1000)
    void synOnceTaoBaoKeOrderTwoMinus() {
        service.execute(() -> {
            logger.error("synOnceTaoBaoKeOrderTwoMinus");
            synOnceTaoBaoKeOrder();
        });
    }

    //同步订单 默认值
    private static Integer order = 1;

    public Result tallyOrderTao() {
        //判断是否有订单正在同步中
        if (order == 2) {
            return ResultUtil.error(-100, "订单正在同步中，请稍等片刻！");
        }
        order = 2;
        service.execute(this::getTallyOrderTao);
        return ResultUtil.success();
    }


    /**
     * 获取当月付款订单每天凌晨2点
     */
    @Scheduled(cron = "0 0 2 * * ?")
    void synCurrMonthTaoBaoKeOrderLastOneDian() {
        service.execute(() -> synCurrMonthTaoBaoKeOrder(2L));
        //拼多多订单
        service.execute(this::sysPddMonthOrder);
        //京东
        service.execute(this::getJdOrders);
        //美团
        service.execute(this::sysMTMonthOrder);
        //多麦
        service.execute(this::sysDMMonthOrder);
        //聚推客
        service.execute(this::sysJTKMonthOrder);
        //抖音
        service.execute(this::sysDYMonthOrder);
        //唯品会
        service.execute(this::sysWphMonthOrder);
    }

    /**
     * 获取当月淘宝结算订单每天3点
     */
    @Scheduled(cron = "0 0 3 * * ?")
    void getTaoBaoOrder() {
        service.execute(() -> {
            synCurrMonthTaoBaoKeOrder(3L);
        });
    }

    /**
     * 每个月25号凌晨0点自动结算
     */
    @Scheduled(cron = "0 0 0 25 * ?")
    void CashMoney() {
        service.execute(() -> {
            iCashService.userToTalMoney();
        });
    }


    private void getTallyOrderTao() {
        Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
        //同步完毕时间，当前日期
        Date closeTime = new Date();
        CommonInfo appkey;
        CommonInfo tbName;
        CommonInfo one = commonRepository.findOne(89);
        if ("1".equals(one.getValue())) {
            //获取淘宝的appkey
            appkey = commonRepository.findOne(6);
            //获取淘宝的秘钥
            tbName = commonRepository.findOne(7);
        } else {
            appkey = commonRepository.findOne(30);
            tbName = commonRepository.findOne(11);
        }



        /**/
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        while (closeTime.getTime() >= startTime.getTime()) {
            //结束时间
            Date endTime = DateUtil.getLaterMinute(startTime, 20L);
            Date finalStartTime = startTime;
            service.execute(() -> {
                try {
                    //查渠道订单
                    getTaoBaoOrder(1, 2L, null, 2L, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                    Thread.sleep(2 * 1000);
                    getTaoBaoOrder(1, 1L, null, 2L, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                } catch (Exception e) {
                    //打印错误信息，并再次同步
                    e.printStackTrace();
                    logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                }
            });
            service.execute(() -> {
                try {
                    //查渠道订单
                    getTaoBaoOrder(1, 2L, null, 3L, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                    Thread.sleep(2 * 1000);
                    getTaoBaoOrder(1, 1L, null, 3L, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                } catch (Exception e) {
                    //打印错误信息，并再次同步
                    e.printStackTrace();
                    logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                }
            });
            service.execute(() -> {
                try {
                    //查渠道订单
                    getPddOrder(finalStartTime.getTime() / 1000, endTime.getTime() / 1000, clientId, clientSecret);//渠道, 结算时间
                    //计算下一次开始时间
                } catch (Exception e) {
                    //打印错误信息，并再次同步
                    e.printStackTrace();
                    logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                }
            });
            try {
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //计算下一次开始时间
            startTime = DateUtil.getLaterMinute(startTime, 20L);
        }
        sysMTMonthOrder();
        getJdOrders();
        sysDMMonthOrder();
        sysJTKMonthOrder();
        sysDYMonthOrder();
        sysWphMonthOrder();
        order = 1;
    }


    private void getJdOrders() {
        try {
            Date endTime = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            //查询时间，建议使用分钟级查询，格式：yyyyMMddHH、yyyyMMddHHmm或yyyyMMddHHmmss，如201811031212 的查询范围从12:12:00--12:12:59
            //订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.getActualMinimum(Calendar.DAY_OF_MONTH), 00, 00, 00);
            Date startTime = cal.getTime();
            CommonInfo one = commonRepository.findOne(13);
            //京东秘钥
            CommonInfo two = commonRepository.findOne(14);
            while (startTime.getTime() <= endTime.getTime()) {
                System.err.println(sdf.format(startTime.getTime()));
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getJdOrder(1, sdf.format(finalStartTime.getTime()), one, two);
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getJdOrder(2, sdf.format(finalStartTime.getTime()), one, two);
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getJdOrder(3, sdf.format(finalStartTime.getTime()), one, two);
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                Thread.sleep(5 * 1000);
                startTime = DateUtil.getLaterMinute(startTime, 60L);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private void getJdOrder() {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
            //查询时间，建议使用分钟级查询，格式：yyyyMMddHH、yyyyMMddHHmm或yyyyMMddHHmmss，如201811031212 的查询范围从12:12:00--12:12:59
            //订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
            CommonInfo one = commonRepository.findOne(13);
            //京东秘钥
            CommonInfo two = commonRepository.findOne(14);
            getJdOrder(1, sdf.format(new Date()), one, two);
            Thread.sleep(5 * 1000);
            getJdOrder(2, sdf.format(new Date()), one, two);
            Thread.sleep(5 * 1000);
            getJdOrder(3, sdf.format(new Date()), one, two);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 同步本月美团订单
     */
    private void sysMTMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo clientId = commonRepository.findOne(123);
            CommonInfo clientSecret = commonRepository.findOne(124);
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 20L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"1",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"2",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"3",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"4",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"5",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"9",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getMeiOrder(finalStartTime.getTime()/1000,endTime.getTime()/1000,"10",clientId,clientSecret,1);
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                startTime = DateUtil.getLaterMinute(startTime,24 * 60L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }

    private void getMTOrder() {
        CommonInfo clientId = commonRepository.findOne(123);
        CommonInfo clientSecret = commonRepository.findOne(124);
        /*CommonInfo actId1 = commonRepository.findOne(127);
        CommonInfo actId2 = commonRepository.findOne(132);
        CommonInfo actId3 = commonRepository.findOne(138);
        CommonInfo actId4 = commonRepository.findOne(139);*/
        //获取过去60分钟的订单
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"1" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"2" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"3" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"4" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"5" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"9" ,clientId, clientSecret,1);
        getMeiOrder(System.currentTimeMillis()/1000 -(24 * 60 * 60), System.currentTimeMillis()/1000,"10" ,clientId, clientSecret,1);

        //getMeiOrder(System.currentTimeMillis()/1000 -(120 * 60 * 1000), System.currentTimeMillis()/1000,6 ,clientId, clientSecret,1);

    }



    /**
     * 同步本月多麦订单
     */
    private void sysDMMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo clientId = commonRepository.findOne(201);
            CommonInfo clientSecret = commonRepository.findOne(202);
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 24 * 60L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getDuoMai(finalStartTime.getTime()/1000,endTime.getTime()/1000,clientId,clientSecret,"1");
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                startTime = DateUtil.getLaterMinute(startTime,24 * 60L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }


    /**
     * 同步本月聚推客订单
     */
    private void sysJTKMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            String apikey = commonRepository.findOne(266).getValue();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 60L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getJTK(sdf.format(finalStartTime) , sdf.format(endTime),apikey,"1");
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                startTime = DateUtil.getLaterMinute(startTime,60L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }


    /**
     * 同步本月抖音订单
     */
    private void sysDYMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo clientId = commonRepository.findOne(238);
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 24 * 60L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getDouYin(finalStartTime.getTime()/1000,endTime.getTime()/1000,clientId,"1","1");
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        getDouYin(finalStartTime.getTime()/1000,endTime.getTime()/1000,clientId,"1","2");
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                startTime = DateUtil.getLaterMinute(startTime,24 * 60L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }


    /**
     * 同步本月唯品会订单
     */
    private void sysWphMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo appkey = commonRepository.findOne(30);
            CommonInfo key = commonRepository.findOne(239);
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 24 * 60L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        getWph(finalStartTime.getTime()/1000,endTime.getTime()/1000,appkey,key,"1");
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                startTime = DateUtil.getLaterMinute(startTime,24 * 60L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }



    /**
     * 每分钟同步前60分钟的订单
     */
    private void synOnceTaoBaoKeOrders() {
        try {
            Date endTime = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, -1);
            Date startTime = calendar.getTime();
            CommonInfo appkey;
            CommonInfo tbName;
            CommonInfo one = commonRepository.findOne(89);
            if ("1".equals(one.getValue())) {
                //获取淘宝的appkey
                appkey = commonRepository.findOne(6);
                //获取淘宝的秘钥
                tbName = commonRepository.findOne(7);
            } else {
                appkey = commonRepository.findOne(30);
                tbName = commonRepository.findOne(11);
            }
            while (startTime.getTime() <= endTime.getTime()) {
                Date finalStartTime = startTime;
                Date closeDate = DateUtil.getLaterMinute(startTime, 20L);
                service.execute(() -> {
                    try {
                        //查渠道订单
                        getTaoBaoOrder(1, 2L, null, 2L, finalStartTime, closeDate, appkey, tbName);//渠道, 付款时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                service.execute(() -> {
                    try {
                        //查渠道订单
                        getTaoBaoOrder(1, 2L, null, 3L, finalStartTime, closeDate, appkey, tbName);//渠道, 结算时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                Thread.sleep(3 * 1000);
                startTime = DateUtil.getLaterMinute(startTime, 20L);
            }
        } catch (Exception e) {
            logger.error("=========每分钟同步前20分钟的订单----订单同步异常=========");
            e.printStackTrace();
        }
    }


    /**
     * 每分钟同步前20分钟的订单
     */
    private void synOnceTaoBaoKeOrder() {
        try {
            Date endTime = new Date();
            CommonInfo appkey;
            CommonInfo tbName;
            CommonInfo one = commonRepository.findOne(89);
            if ("1".equals(one.getValue())) {
                //获取淘宝的appkey
                appkey = commonRepository.findOne(6);
                //获取淘宝的秘钥
                tbName = commonRepository.findOne(7);
            } else {
                appkey = commonRepository.findOne(30);
                tbName = commonRepository.findOne(11);
            }
            //时间跨度不能超过20分钟 当前时间往前20分钟
            Date startTime = DateUtil.getPreviouslyMinute(endTime, 20L);
            getTaoBaoOrder(1, 2L, null, 2L, startTime, endTime, appkey, tbName);//渠道, 付款时间
            Thread.sleep(2 * 1000);
            getTaoBaoOrder(1, 2L, null, 3L, startTime, endTime, appkey, tbName);//渠道, 结算时间
            Thread.sleep(2 * 1000);
            getTaoBaoOrder(1, 1L, null, 2L, startTime, endTime, appkey, tbName);//渠道, 付款时间
            Thread.sleep(2 * 1000);
            getTaoBaoOrder(1, 1L, null, 3L, startTime, endTime, appkey, tbName);//渠道, 付款时间
        } catch (Exception e) {
            logger.error("=========每分钟同步前20分钟的订单----订单同步异常=========");
            e.printStackTrace();
        }
    }

    /**
     * 同步淘宝当月所有订单
     */
    private void synCurrMonthTaoBaoKeOrder(long type) {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo appkey;
            CommonInfo tbName;
            CommonInfo one = commonRepository.findOne(89);
            if ("1".equals(one.getValue())) {
                //获取淘宝的appkey
                appkey = commonRepository.findOne(6);
                //获取淘宝的秘钥
                tbName = commonRepository.findOne(7);
            } else {
                appkey = commonRepository.findOne(30);
                tbName = commonRepository.findOne(11);
            }
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 20L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        //查渠道订单
                        getTaoBaoOrder(1, 2L, null, type, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                        Thread.sleep(3 * 1000);
                        //查询常规订单
                        getTaoBaoOrder(1, 1L, null, type, finalStartTime, endTime, appkey, tbName);//渠道, 结算时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                Thread.sleep(3 * 1000);
                //计算下一次开始时间
                startTime = DateUtil.getLaterMinute(startTime, 20L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }

    /**
     * @param orderScene    场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
     * @param positionIndex 位点，除第一页之外，都需要传递；前端原样返回。
     * @param type          查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
     * @param endTime       订单查询结束时间，订单开始时间至订单结束时间，中间时间段日常要求不超过3个小时，但如618、双11、年货节等大促期间预估时间段不可超过20分钟，超过会提示错误，调用时请务必注意时间段的选择，以保证亲能正常调用！
     * @param startDate     订单查询开始时间
     * @return
     */
   /* private void getTaoBaoOrder(Integer page, Long orderScene, String positionIndex, Long type, Date startDate, Date endTime,CommonInfo appkey,CommonInfo tbName) {
        try {
            if (sdf == null) {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            Map<String,String> map=new HashMap<>();
            map.put("apkey",appkey.getValue());//APKEY秘钥
            map.put("query_type",String.valueOf(type));//查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
            map.put("position_index",positionIndex);//位点，除第一页之外，都需要传递；前端原样返回。
            map.put("page_size",String.valueOf(100));//页大小，默认20，1~100
            //map.put("member_type",);//推广者角色类型,2:二方，3:三方，不传，表示所有角
            //map.put("tk_status",);//淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
            map.put("end_time",sdf.format(endTime));//订单查询结束时间，订单开始时间至订单结束时间，中间时间段日常要求不超过3个小时，但如618、双11、年货节等大促期间预估时间段不可超过20分钟，超过会提示错误，调用时请务必注意时间段的选择，以保证亲能正常调用！空格以+代替或者进行urlencode编码
            map.put("start_time",sdf.format(startDate));//订单查询开始时间，空格以+代替或者进行urlencode编码
            //map.put("jump_type",);//跳转类型，当向前或者向后翻页必须提供,-1: 向前翻页,1：向后翻页
            map.put("page_no",String.valueOf(page));//第几页，默认1，1~100
            map.put("order_scene",String.valueOf(orderScene));//场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
            map.put("tbname",tbName.getValue());//在本平台授权的淘客账号所对应的用户名，见“会员中心”-“账号授权”-“淘宝授权”列表页
            String body = HttpClientUtil.doGet("http://api.web.21ds.cn/taoke/tbkOrderDetailsGet", map);
            logger.error("=========getTaoBaoOrder==============" + body);
            if(StringUtils.isNotBlank(body)){
                JSONObject bodyJson = JSON.parseObject(body);
                String code = bodyJson.getString("code");
                if(StringUtils.isNotBlank(code) && code.equals("200")){
                    JSONObject dataJson = bodyJson.getJSONObject("data");
                    String list = dataJson.getString("list");
                    List<PublisherOrderDtoBean> publisher_order_dto = JSONArray.parseArray(list, PublisherOrderDtoBean.class);
                    if (publisher_order_dto != null && publisher_order_dto.size() > 0) {
                        logger.info("=========TaoBao save order==============" + publisher_order_dto.size());
                        saveTaoBaoKeOrder(publisher_order_dto);
                    }
                    if (dataJson.getBooleanValue("has_next")) {
                        getTaoBaoOrder(++page, orderScene, dataJson.getString("position_index"), type, startDate, endTime,appkey,tbName);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("=========请求报错==============" + e);
        }

    }*/
    private void getTaoBaoOrder(Integer page, Long orderScene, String positionIndex, Long type, Date startDate, Date endTime, CommonInfo one, CommonInfo two) {
        CommonInfo one1 = commonRepository.findOne(89);
        if ("2".equals(one1.getValue())) {
            try {
                if (sdf == null) {
                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                }
                Map<String, String> map = new HashMap<>();
                map.put("apkey", one.getValue());//APKEY秘钥
                map.put("query_type", String.valueOf(type));//查询时间类型，1：按照订单淘客创建时间查询，2:按照订单淘客付款时间查询，3:按照订单淘客结算时间查询
                map.put("position_index", positionIndex);//位点，除第一页之外，都需要传递；前端原样返回。
                map.put("page_size", String.valueOf(100));//页大小，默认20，1~100
                //map.put("member_type",);//推广者角色类型,2:二方，3:三方，不传，表示所有角
                //map.put("tk_status",);//淘客订单状态，12-付款，13-关闭，14-确认收货，3-结算成功;不传，表示所有状态
                map.put("end_time", sdf.format(endTime));//订单查询结束时间，订单开始时间至订单结束时间，中间时间段日常要求不超过3个小时，但如618、双11、年货节等大促期间预估时间段不可超过20分钟，超过会提示错误，调用时请务必注意时间段的选择，以保证亲能正常调用！空格以+代替或者进行urlencode编码
                map.put("start_time", sdf.format(startDate));//订单查询开始时间，空格以+代替或者进行urlencode编码
                //map.put("jump_type",);//跳转类型，当向前或者向后翻页必须提供,-1: 向前翻页,1：向后翻页
                map.put("page_no", String.valueOf(page));//第几页，默认1，1~100
                map.put("order_scene", String.valueOf(orderScene));//场景订单场景类型，1:常规订单，2:渠道订单，3:会员运营订单，默认为1
                map.put("tbname", two.getValue());//在本平台授权的淘客账号所对应的用户名，见“会员中心”-“账号授权”-“淘宝授权”列表页
                String body = HttpClientUtil.doGet(Config.MIAOYOUQUN_URL+"/taoke/tbkOrderDetailsGet", map);
                logger.error("=========getTaoBaoOrder==============" + body);
                if (StringUtils.isNotBlank(body)) {
                    JSONObject bodyJson = JSON.parseObject(body);
                    String code = bodyJson.getString("code");
                    if (StringUtils.isNotBlank(code) && code.equals("200")) {
                        JSONObject dataJson = bodyJson.getJSONObject("data");
                        String list = dataJson.getString("list");
                        List<PublisherOrderDtoBean> publisher_order_dto = JSONArray.parseArray(list, PublisherOrderDtoBean.class);
                        if (publisher_order_dto != null && publisher_order_dto.size() > 0) {
                            logger.info("=========TaoBao save order==============" + publisher_order_dto.size());
                            saveTaoBaoKeOrder(publisher_order_dto);
                        }
                        if (dataJson.getBooleanValue("has_next")) {
                            getTaoBaoOrder(++page, orderScene, dataJson.getString("position_index"), type, startDate, endTime, one, two);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("=========请求报错==============" + e);
            }
        } else {
            try {
                if (sdf == null) {
                    sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                }

                TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", one != null ? one.getValue() : Config.TaoAppKey, two != null ? two.getValue() : Config.TaoSecret);

                TbkOrderDetailsGetRequest req = new TbkOrderDetailsGetRequest();
                req.setQueryType(type);
                req.setPageSize(100L);
                req.setEndTime(sdf.format(endTime));
                req.setStartTime(sdf.format(startDate));
                if (positionIndex != null) {
                    req.setPositionIndex(positionIndex);
                }
                req.setPageNo(Long.valueOf(page));
                req.setOrderScene(orderScene);
                TbkOrderDetailsGetResponse rsp = client.execute(req);
                String body = rsp.getBody();
                logger.error("=========getTaoBaoOrder==============" + body);
                if (StringUtils.isNotBlank(body)) {
                    JSONObject orderResponse = null;
                    for (int i = 0; i < 3; i++) {
                        try {
                            orderResponse = JSON.parseObject(body).getJSONObject("tbk_order_details_get_response").getJSONObject("data");
                            break;
                        } catch (NullPointerException e) {
                            try {
                                //系统繁忙则停顿三秒后调用
                                Thread.sleep(3000);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }
                            rsp = client.execute(req);
                        }
                        body = rsp.getBody();
                    }
                    if (orderResponse != null) {
                        TaoOrder taoOrder = JSON.parseObject(body, TaoOrder.class);
                        List<PublisherOrderDtoBean> publisher_order_dto = taoOrder.getTbk_order_details_get_response().getData().getResults().getPublisher_order_dto();
                        if (publisher_order_dto != null && publisher_order_dto.size() > 0) {
                            logger.info("=========TaoBao save order==============" + publisher_order_dto.size());
                            saveTaoBaoKeOrder(publisher_order_dto);
                        }
                        if (orderResponse.getBooleanValue("has_next")) {
                            getTaoBaoOrder(++page, orderScene, orderResponse.getString("position_index"), type, startDate, endTime, one, two);
                        }
                    }
                }

            } catch (ApiException e) {
                e.printStackTrace();
                logger.info("=========请求报错==============" + e);
            }
        }


    }


    /**
     * //维权状态，0 ：非维权，1：维权订单
     * //订单状态，3：订单结算，12：订单付款， 13：订单失效，14：订单成功
     * //收支状态，0 无效  1 冻结  2 有效
     * 处理创建订单
     *
     * @param
     */
    private void saveTaoBaoKeOrder(List<PublisherOrderDtoBean> publisher_order_dto) {
        for (PublisherOrderDtoBean o : publisher_order_dto) {
            long relationId = o.getRelation_id();
            String fee = o.getPub_share_pre_fee();

            UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(relationId));
            if (userInfo != null) {
                getRate(o, userInfo, Float.parseFloat(String.valueOf(fee)) / 100, new DecimalFormat("#########.##"), null);
            }

            switch (o.getTk_status()) {
                case 12:
                    //付款
                    logger.info("====================Payed order=====================");
                    saveOrderInfoCondition(o);
                    break;
                case 3:
                    //结算
                    logger.error("=====================结算订单=====================");
                    updateJieSuanOrder(o);
                    break;
                case 13:
                    //退款
                    logger.error("=====================退款订单=====================");
                    saveExitOrderInfoCondition(o);
                    break;
                default:
                    logger.error("=====================其他订单=====================");
                    saveOrderInfoCondition(o);
                    break;
            }
        }
    }
//    private void saveTaoBaoKeOrder(List<PublisherOrderDtoBean> publisher_order_dto) {
//        for (PublisherOrderDtoBean o : publisher_order_dto) {
//            switch (o.getTk_status()) {
//                case 12:
//                    //付款
//                    logger.info("====================Payed order=====================");
//                    saveOrderInfoCondition(o);
//                    break;
//                case 3:
//                    //结算
//                    logger.error("=====================结算订单=====================");
//                    updateJieSuanOrder(o);
//                    break;
//                case 13:
//                    //退款
//                    logger.error("=====================退款订单=====================");
//                    saveExitOrderInfoCondition(o);
//                    break;
//                default:
//                    logger.error("=====================其他订单=====================");
//                    saveOrderInfoCondition(o);
//                    break;
//            }
//        }
//    }

    /**
     * 处理淘宝结算订单数据
     *
     * @param
     */
    private void updateJieSuanOrder(PublisherOrderDtoBean o) {
        DecimalFormat df = new DecimalFormat("#########.##");
        //通过订单号查询用户的订单信息 检查是否已经存储到数据库
        PublisherOrderDtoBean publisherOrderDtoBean;
        try {
            publisherOrderDtoBean = orderRepository.findByRelationIdCount(o.getTrade_id());
        } catch (Exception e) {
            //当发现有多个订单时 删除重复的订单
            List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(o.getTrade_id());
            for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
                orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
            }
            publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
        }

        //如果订单已经存在进入这里执行
        if (publisherOrderDtoBean != null) {
            publisherOrderDtoBean.setTk_status(3);
            //通过私域账号查询用户的信息
            UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(o.getRelation_id()));
            if (userInfo != null) {
                setUserOrderJiFen(publisherOrderDtoBean, df, userInfo);
                //处理卡券抵扣业务
                handleCouponOrder(publisherOrderDtoBean,userInfo,"TB","3");
            }
        } else {
            saveOrderInfoCondition(o);
            UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(o.getRelation_id()));
            if(userInfo!=null){
                if(Integer.valueOf("12").equals(o.getTk_status())){
                    //处理卡券抵扣业务
                    handleCouponOrder(publisherOrderDtoBean,userInfo,"TB","12");
                }else if(Integer.valueOf("13").equals(o.getTk_status())){
                    //处理卡券抵扣业务
                    handleCouponOrder(publisherOrderDtoBean,userInfo,"TB","13");
                }
            }
        }
    }


    /**
     * 退款订单处理
     *
     * @param o
     */
    private void saveExitOrderInfoCondition(PublisherOrderDtoBean o) {
        //获取当前订单是否已经存储过
        PublisherOrderDtoBean publisherOrderDtoBean;
        try {
            publisherOrderDtoBean = orderRepository.findByRelationIdCount(o.getTrade_id());
        } catch (Exception e) {
            //当发现有多个订单时 删除重复的订单
            List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(o.getTrade_id());
            for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
                orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
            }
            publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
        }
        UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(o.getRelation_id()));
        if (publisherOrderDtoBean != null) {
            publisherOrderDtoBean.setTk_status(13);
            orderJpaRepository.save(publisherOrderDtoBean);
            //抵扣额度
            handleCouponOrder(o,userInfo,"TB","13");
        } else {
            saveOrderInfoCondition(o);
            //处理卡券抵扣业务
            if(Integer.valueOf("12").equals(o.getTk_status())){
                //处理卡券抵扣业务
                handleCouponOrder(o,userInfo,"TB","12");
            }else if(Integer.valueOf("3").equals(o.getTk_status())){
                handleCouponOrder(o,userInfo,"TB","3");
            }
        }


    }

    /**
     * 处理淘宝付款订单业务
     *
     * @param o
     */
    private void saveOrderInfoCondition(PublisherOrderDtoBean o) {
        DecimalFormat df = new DecimalFormat("#########.##");
        //获取当前订单的用户信息
        UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(o.getRelation_id()));
        //初始化订单不是免单 0表示不是免单
        o.setIsGif(0);
        //订单是否积分 0表示没有积分
        o.setIsJifen(0);
        //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
        o.setBalance(0);
        //获取订单的总佣金
        float d = Float.parseFloat(o.getPub_share_pre_fee());
        //判断是淘宝订单还是饿了么订单
        if("饿了么".equals(o.getOrder_type())){
            o.setFromInfo("elm");
        }else{
            o.setFromInfo("tb");
        }
        //检查是不是新用户（获取用户订单 列表没有订单表示是新用户） 新人首次下单
        newsUserDownOrder(o, userInfo, d, df);
        if(Integer.valueOf("12").equals(o.getTk_status())){
                //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"TB","12");
        }
    }

    private void updatePddOrders() {
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        //获取过去60分钟的订单
        getPddOrder(System.currentTimeMillis() / 1000 - 60 * 60, System.currentTimeMillis() / 1000, clientId, clientSecret);
    }


    private void updatePddOrder() {
        CommonInfo clientId = commonRepository.findOne(23);
        CommonInfo clientSecret = commonRepository.findOne(24);
        //获取过去20分钟的订单
        getPddOrder(System.currentTimeMillis() / 1000 - 60 * 20, System.currentTimeMillis() / 1000, clientId, clientSecret);
    }

    private void updateDuoMaiOrder() {
        CommonInfo clientId = commonRepository.findOne(201);
        CommonInfo clientSecret = commonRepository.findOne(202);
        //获取过去一天
        getDuoMai(System.currentTimeMillis() / 1000 - 60 * 60 * 24, System.currentTimeMillis() / 1000, clientId, clientSecret,"1");
    }

    private void updateJTKOrder() {
        String apikey = commonRepository.findOne(266).getValue();
        //获取1小时前
        Date date = new Date();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        getJTK(sdf.format(DateUtil.getPreviouslyMinute(date,60L)) , sdf.format(date),apikey,"1");
    }

    private void updateDouYinOrder() {
        CommonInfo clientId = commonRepository.findOne(238);
        //获取过去一天
        getDouYin(System.currentTimeMillis() / 1000 - 60 * 60 * 24, System.currentTimeMillis() / 1000, clientId,"1","1");

        getDouYin(System.currentTimeMillis() / 1000 - 60 * 60 * 24, System.currentTimeMillis() / 1000, clientId,"1","2");
    }

    private void updateWphOrder() {
        CommonInfo appkey = commonRepository.findOne(30);
        CommonInfo key = commonRepository.findOne(239);
        //获取过去一天
        getWph(System.currentTimeMillis()  - 60 * 60 * 1000, System.currentTimeMillis() , appkey,key,"1");
    }


    private void sysPddMonthOrder() {
        try {
            Date startTime = DateUtil.lowDate(DateUtil.getFirstDayOfMonth());
            //同步完毕时间，当前日期
            Date closeTime = new Date();
            CommonInfo clientId = commonRepository.findOne(23);
            CommonInfo clientSecret = commonRepository.findOne(24);
            while (closeTime.getTime() >= startTime.getTime()) {
                //结束时间
                Date endTime = DateUtil.getLaterMinute(startTime, 20L);
                Date finalStartTime = startTime;
                service.execute(() -> {
                    try {
                        //查渠道订单
                        getPddOrder(finalStartTime.getTime() / 1000, endTime.getTime() / 1000, clientId, clientSecret);//渠道, 结算时间
                        //计算下一次开始时间
                    } catch (Exception e) {
                        //打印错误信息，并再次同步
                        e.printStackTrace();
                        logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
                    }
                });
                Thread.sleep(3 * 1000);
                startTime = DateUtil.getLaterMinute(startTime, 20L);
            }
        } catch (Exception e) {
            //打印错误信息，并再次同步
            e.printStackTrace();
            logger.error(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(DateUtil.lowDate(DateUtil.getFirstDayOfMonth())) + "=========同步当月1号到15号的所有订单=========");
        }
    }

    /**
     * 获取拼多多订单
     */
    private void getPddOrder(Long startTime, Long endTime, CommonInfo clientId, CommonInfo clientSecret) {
        try {
            PopClient client = new PopHttpClient(clientId != null ? clientId.getValue() : Config.clientId, clientSecret != null ? clientSecret.getValue() : Config.clientSecret);
//            client = new PopHttpClient("5027983e794e4b01bb390de3651a8164","64c91b13bd591cb76a7db66a6204e92465ce02d5");
            PddDdkOrderListIncrementGetRequest request = new PddDdkOrderListIncrementGetRequest();
            request.setStartUpdateTime(startTime);
            request.setEndUpdateTime(endTime);
            request.setPageSize(100);
            request.setPage(1);
            request.setReturnCount(false);
            PddDdkOrderListIncrementGetResponse response = client.syncInvoke(request);
            System.out.print(JsonUtil.transferToJson(response));
            PddDdkOrderListIncrementGetResponse.OrderListGetResponse orderListGetResponse = response.getOrderListGetResponse();
            if (orderListGetResponse != null) {
                String s = JsonUtil.transferToJson(orderListGetResponse.getOrderList());
                logger.error("=========getPddOrder==============" + s);
                List<PddOrder> pddOrders = JSON.parseArray(s, PddOrder.class);
                pddJpaRepository.saveAll(pddOrders);
                for (PddOrder p : pddOrders) {
                    saveOrder(p);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void getWph(Long startTime, Long endTime, CommonInfo apikey,CommonInfo key, String page){
        //喵有券
        String url="http://api.web.ecapi.cn/vip/getOrderList";
        Map<String,String> map=new HashMap<>();
        map.put("apkey",apikey.getValue());
        map.put("key",key.getValue());
        map.put("page",page);
        map.put("pageSize","100");
        map.put("orderTimeStart",String.valueOf(startTime));
        map.put("orderTimeEnd",String.valueOf(endTime));
        String s1 = HttpClientUtil.doGet(url, map);
        log.error("唯品会---------------------"+s1);
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray orderInfoList = data.getJSONArray("orderInfoList");
        Integer total = data.getInteger("total");
        if(orderInfoList!=null){
            saveWPHOrder(orderInfoList);
            int pages = Integer.parseInt(page);
            int tos=pages*100;
            if(total>tos){
                pages++;
                getWph(startTime,endTime,apikey,key,String.valueOf(pages));
            }
        }
    }

    private void saveWPHOrder(JSONArray dataList){
        DecimalFormat df = new DecimalFormat("#########.##");
        for(int i=0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String orderCode = jsonObject.getString("orderSn");//订单号
            String payTime = jsonObject.getString("orderTime");//支付时间
            String orderLineStatusDesc = jsonObject.getString("orderSubStatusName");//订单状态
            String productName = jsonObject.getJSONArray("detailList").getJSONObject(0).getString("goodsName");//商品名称
            String goodsImg = jsonObject.getJSONArray("detailList").getJSONObject(0).getString("goodsThumb");//商品图
            String payAmount = jsonObject.getString("totalCost");//实付金额
            String sid = jsonObject.getString("channelTag");//子推广账号ID(sid)
            String prePayCommission = jsonObject.getString("commission");//预估佣金
            UserInfo userInfo=null;
            if(StringUtils.isNotEmpty(sid)){
                userInfo=userRepository.getUserByRelationId(sid);
            }
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderCode);
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderCode);
                for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("wph");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                if(userInfo!=null){
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                }
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("唯品会");
                o.setItem_num(1);
                //商品图片
                o.setItem_img(goodsImg);
                //商品标题
                o.setItem_title(productName);
                //订单编号
                o.setTrade_id(orderCode);
                o.setTrade_parent_id(orderCode);
                //商品id
                o.setItem_id("0");
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(payAmount)));
                float d = Float.parseFloat(prePayCommission);
                //设置佣金金额
                o.setPub_share_pre_fee(prePayCommission);
                //实际支付金额
                o.setAlipay_total_price(payAmount);
                //订单支付时间
                o.setTb_paid_time(payTime);
                //订单支付时间
                o.setTk_paid_time(payTime);
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                //处理订单状态 这里处理已付款状态
                setWPHStatus(orderLineStatusDesc, publisherOrderDtoBean);
            }
        }
    }




    private void getDouYin(Long startTime, Long endTime, CommonInfo apikey, String page,String type){
        String url="https://v2.api.haodanku.com/dy_order_list";
        Map<String,String> map=new HashMap<>();
        map.put("start_date",String.valueOf(startTime));//开始时间
        map.put("end_date",String.valueOf(endTime));//结束时间
        map.put("apikey",apikey.getValue());//应用中心获取Apikey值
        map.put("min_id",page);//页码
        map.put("date_type","4");//1.付款时间（默认付款）、2.结算时间、3.失效时间、4.更新时间
        map.put("back","100");//每页条数（最大100条）
        map.put("media_type",type);//媒体类型：1物料商品、2直播商品

        String s1 = HttpClientUtil.doPost(url, map);
        log.error("抖音---------------------"+s1);
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONArray data = jsonObject.getJSONArray("data");
        saveDouYinOrder(data);
        int pages = Integer.parseInt(page);
        if(data.size()>=100){
            pages++;
            getDouYin(startTime,endTime,apikey,String.valueOf(pages),type);
        }

    }


    private void saveDouYinOrder(JSONArray dataList){
        DecimalFormat df = new DecimalFormat("#########.##");
        for(int i=0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String orderCode = jsonObject.getString("trade_id");//订单号
            String payTime = jsonObject.getString("paid_time");//支付时间
            String orderLineStatusDesc = jsonObject.getString("order_status");//订单状态
            String productName = jsonObject.getString("item_title");//商品名称
            String goodsImg = jsonObject.getString("item_img");//商品图
            String payAmount = jsonObject.getString("pay_price");//实付金额
            String sid = jsonObject.getString("channel_code");//子推广账号ID(sid)
            String prePayCommission = jsonObject.getString("predict_money");//预估佣金
            String actualMoney = jsonObject.getString("actual_money");//实际佣金
            if(StringUtils.isNotEmpty(actualMoney) && !"0.00".equals(actualMoney)){
                prePayCommission=actualMoney;
            }
            UserInfo userInfo=null;
            if(StringUtils.isNotEmpty(sid)){
                userInfo=userRepository.getUserByInvitationCode(sid);
            }
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderCode);
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderCode);
                for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("dy");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                if(userInfo!=null){
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                }
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("抖音");
                o.setItem_num(1);
                //商品图片
                o.setItem_img(goodsImg);
                //商品标题
                o.setItem_title(productName);
                //订单编号
                o.setTrade_id(orderCode);
                o.setTrade_parent_id(orderCode);
                //商品id
                o.setItem_id("0");
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(payAmount)));
                float d = Float.parseFloat(prePayCommission);
                //设置佣金金额
                o.setPub_share_pre_fee(prePayCommission);
                //实际支付金额
                o.setAlipay_total_price(payAmount);

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long lt = new Long(payTime+"000");
                Date date = new Date(lt);
                payTime = simpleDateFormat.format(date);

                //订单支付时间
                o.setTb_paid_time(payTime);
                //订单支付时间
                o.setTk_paid_time(payTime);
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                //处理订单状态 这里处理已付款状态
                setDouYinStatus(orderLineStatusDesc, publisherOrderDtoBean);
            }
        }
    }



    private void getDuoMai(Long startTime, Long endTime, CommonInfo clientId, CommonInfo clientSecret,String page){
        StringBuilder url=new StringBuilder("https://open.duomai.com/apis?");
        Map<String,String> map=new HashMap<>();
        map.put("stime",String.valueOf(startTime));
        map.put("etime",String.valueOf(endTime));
        map.put("page",page);
        map.put("page_size","100");
        String timestamp=(System.currentTimeMillis()/1000)+"";
        String sign = clientSecret.getValue() + "app_key" + clientId.getValue() + "servicecps-mesh.open.orders.query.get" +
                "timestamp" + timestamp + JSONObject.toJSONString(map) + clientSecret.getValue();
        String s = MD5Util.md5Encrypt32Upper(sign);
        url.append("app_key=").append(clientId.getValue()).append("&sign=").append(s).append("&service=cps-mesh.open.orders.query.get");
        url.append("&timestamp=").append(timestamp);
        String s1 = HttpClientUtil.doPostJson(url.toString(), JSONObject.toJSONString(map));
        log.error("多麦---------------------"+s1);
        JSONObject jsonObject = JSON.parseObject(s1);
        JSONObject pagination = jsonObject.getJSONObject("pagination");
        Integer total = pagination.getInteger("total");
        int pages = Integer.parseInt(page);
        JSONArray data = jsonObject.getJSONArray("data");
        saveDuoMaiOrder(data);
        if(total>(pages*100)){
            pages++;
            getDuoMai(startTime,endTime,clientId,clientSecret,String.valueOf(pages));
        }

    }


    private void saveDuoMaiOrder(JSONArray dataList){
        DecimalFormat df = new DecimalFormat("#########.##");
        for(int i=0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String orderCode = jsonObject.getString("order_sn");//订单号
            String payTime = jsonObject.getString("order_time");//支付时间
            String orderLineStatusDesc = jsonObject.getString("status");//订单状态
            JSONArray details = jsonObject.getJSONArray("details");
            String productName = details.getJSONObject(0).getString("goods_name");//商品名称
            String goodsImg = details.getJSONObject(0).getString("goods_img");//商品名称
            String payAmount = jsonObject.getString("orders_price");//实付金额b
            String sid = jsonObject.getString("euid");//子推广账号ID(sid)
            String prePayCommission = jsonObject.getString("siter_commission");//预估佣金
            UserInfo userInfo=null;
            if(StringUtils.isNotEmpty(sid)){
                userInfo=userRepository.getUserByRelationId(sid);
            }
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderCode);
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderCode);
                for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("dm");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                if(userInfo!=null){
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                }
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("多麦");
                o.setItem_num(1);
                //商品图片
                o.setItem_img(goodsImg);
                //商品标题
                o.setItem_title(productName);
                //订单编号
                o.setTrade_id(orderCode);
                o.setTrade_parent_id(orderCode);
                //商品id
                o.setItem_id("0");
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(payAmount)));
                float d = Float.parseFloat(prePayCommission);
                //设置佣金金额
                o.setPub_share_pre_fee(prePayCommission);
                //实际支付金额
                o.setAlipay_total_price(payAmount);
                //订单支付时间
                o.setTb_paid_time(payTime);
                //订单支付时间
                o.setTk_paid_time(payTime);
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                //处理订单状态 这里处理已付款状态
                setDMStatus(orderLineStatusDesc, publisherOrderDtoBean);
            }
        }
    }

    /**
     * 获取聚推客订单
     * @param startTime
     * @param endTime
     * @param apiKey
     * @param page
     */
    private void getJTK(String startTime, String endTime, String apiKey,String page){
        Map<String,String> map=new HashMap<>();
        map.put("apikey",apiKey);
        map.put("start_time",String.valueOf(startTime));//开始时间与结束时间不能超过1小时
        map.put("end_time",String.valueOf(endTime));
        map.put("query_type","2");//1： 按支付时间 2：按更新时间 3：创建时间 ，默认：3
        map.put("page",page);
        map.put("pageSize","100");
        String s1 = HttpClientUtil.doGet("http://api.jutuike.com/union/orders", map);
        log.error("聚推客---------------------"+s1);
        JSONObject jsonObject = JSON.parseObject(s1);
        String code = jsonObject.getString("code");
        if("1".equals(code)){
            JSONObject data = jsonObject.getJSONObject("data");
            if(data!=null){
                JSONArray dataList = data.getJSONArray("data");
                saveJTKOrders(dataList);
                Integer total = data.getInteger("total");
                int pages = Integer.parseInt(page);
                if(total>(pages*100)){
                    pages++;
                    getJTK(startTime,endTime,apiKey,String.valueOf(pages));
                }
            }
        }


    }


    private void saveJTKOrders(JSONArray dataList){
        DecimalFormat df = new DecimalFormat("#########.##");
        for(int i=0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String orderCode = jsonObject.getString("order_sn");//订单号
            String payTime = jsonObject.getString("pay_time");//支付时间
            String orderLineStatusDesc = jsonObject.getString("status");//订单统一状态，0：未付款 1：已付款 2：待结算 3：已结算 4：无效订单
            String productName = jsonObject.getString("order_title");//商品名称

            String payAmount = jsonObject.getString("pay_price");//实付金额
            String sid = jsonObject.getString("sid");//子推广账号ID(sid)
            String prePayCommission = jsonObject.getString("jtk_share_fee");//预估佣金
            UserInfo userInfo=null;
            if(StringUtils.isNotEmpty(sid)){
                userInfo=userRepository.getUserByRelationId(sid);
            }
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderCode);
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderCode);
                for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("jtk");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                if(userInfo!=null){
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                }
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("聚推客");
                o.setItem_num(1);
                //商品图片
                //商品标题
                o.setItem_title(productName);
                //订单编号
                o.setTrade_id(orderCode);
                o.setTrade_parent_id(orderCode);
                //商品id
                o.setItem_id("0");
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(payAmount)));
                float d = Float.parseFloat(prePayCommission);
                //设置佣金金额
                o.setPub_share_pre_fee(prePayCommission);
                //实际支付金额
                o.setAlipay_total_price(payAmount);
                //订单支付时间
                o.setTb_paid_time(payTime);
                //订单支付时间
                o.setTk_paid_time(payTime);
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                //处理订单状态 这里处理已付款状态
                setJTKStatus(orderLineStatusDesc, publisherOrderDtoBean);
            }
        }
    }



    /**
     * 保存拼多多订单
     *
     * @param pddOrder
     */
    private void saveOrder(PddOrder pddOrder) {
        DecimalFormat df = new DecimalFormat("#########.##");
        //通过拼多多获取用户
        UserInfo userInfo = userRepository.getUserByPdd(pddOrder.getP_id());
        if (userInfo != null) {
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(pddOrder.getOrder_sn());
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(pddOrder.getOrder_sn());
                for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("pdd");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                o.setInvitation(userInfo.getInvitation());
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("拼多多");
                //商品图片
                o.setItem_img("//" + pddOrder.getGoods_thumbnail_url().split("://")[1]);
                //商品标题
                o.setItem_title(pddOrder.getGoods_name());
                //订单编号
                o.setTrade_id(pddOrder.getOrder_sn());
                o.setTrade_parent_id(pddOrder.getOrder_sn());
                //商品id
                o.setItem_id(String.valueOf(pddOrder.getGoods_id()));
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(String.valueOf(pddOrder.getGoods_price() * 0.01))));
                Long promotion_amount = pddOrder.getPromotion_amount();
                //设置佣金金额
                o.setPub_share_pre_fee(df.format(Float.parseFloat(String.valueOf(promotion_amount * 0.01))));
                //实际支付金额
                o.setAlipay_total_price(df.format(Float.parseFloat(String.valueOf(pddOrder.getOrder_amount() * 0.01))));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                //订单支付时间
                o.setTb_paid_time(sdf.format(new Date(Long.parseLong(String.valueOf(pddOrder.getOrder_pay_time() * 1000)))));
                //订单支付时间
                o.setTk_paid_time(sdf.format(new Date(Long.parseLong(String.valueOf(pddOrder.getOrder_pay_time() * 1000)))));
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //计算佣金
                float d = Float.parseFloat(df.format(Float.parseFloat(String.valueOf(promotion_amount * 0.01))));
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                //处理订单状态 这里处理已付款状态
                setStatus(pddOrder, publisherOrderDtoBean, userInfo);
            }
        }
    }


    /**
     * 获取拼多多订单
     *
     * @param type
     * @param time
     */
    private void getJdOrder(Integer type, String time, CommonInfo one, CommonInfo two) {
        try {
            String accessToken = "";
            JdClient client = new DefaultJdClient(Config.JD_URL, accessToken, one != null ? one.getValue() : Config.AppKey, two != null ? two.getValue() : Config.Secret);
            UnionOpenOrderQueryRequest request = new UnionOpenOrderQueryRequest();
            OrderReq orderReq = new OrderReq();
            orderReq.setPageNo(1);
            orderReq.setPageSize(500);
            //订单时间查询类型(1：下单时间，2：完成时间，3：更新时间)
            orderReq.setType(type);
            orderReq.setTime(time);
            request.setOrderReq(orderReq);
            UnionOpenOrderQueryResponse execute = client.execute(request);
            logger.error("now" + new Date().toString());
            logger.error("param" + time);
            logger.error("=========getJDOrder==============" + weixin.popular.util.JsonUtil.toJSONString(execute));
            OrderResp[] data = execute.getData();
            if (execute.getData() != null && data.length > 0) {
                for (OrderResp orderResps : data) {
                    saveJdOrder(orderResps);
                }
            }
        } catch (JdException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询美团订单
     * @param startTime  起始时间  10位时间戳
     * @param endTime   结束时间  10位时间戳
     * @param businessLine 业务线
     * @param clientId  appId
     * @param clientSecret  key
     * @param page 分页
     */
    private void getMeiOrder(Long startTime, Long endTime,String businessLine,CommonInfo clientId, CommonInfo clientSecret,int page){

        Map<String,String> map=new HashMap<>();
        map.put("appkey",clientId.getValue());//	appkey
        map.put("ts",System.currentTimeMillis()/1000+"");//	请求时刻10位时间戳(秒级)，有效期60s
        map.put("businessLine",businessLine);// 活动id
        map.put("queryTimeType","2");//  查询时间类型，枚举值 1 按订单支付时间查询 2 按订单发生修改时间查询
        map.put("startTime",startTime+"");//	查询起始时间10位时间戳，以下单时间为准
        map.put("endTime",endTime+"");//	查询截止时间10位时间戳，以下单时间为准
        map.put("page",page+"");//	分页参数，起始值从1开始
        map.put("limit","100");//  每页显示数据条数，最大值为100
        String[] array={"appkey","ts","businessLine","queryTimeType","startTime","endTime","page","limit"};
        String sign = genSign(map, array, clientSecret.getValue());
        map.put("sign",sign);//请求签名，计算方法参考文档中签名(sign)生成逻辑
        String data = HttpClientUtil.doGet(Config.MT_URL, map);
        JSONObject jsonObject = JSON.parseObject(data);
        logger.error("=========getMeiTuanOrder==============" + jsonObject);
        if(jsonObject!=null){
            JSONArray dataList = jsonObject.getJSONArray("dataList");
            if(dataList!=null){
                saveMTOrder(dataList);
                Integer total = jsonObject.getInteger("total");
                if(total>=100){
                    page++;
                    getMeiOrder(startTime, endTime, businessLine, clientId, clientSecret, page);
                }
            }
        }
    }

    private void saveMTOrder(JSONArray dataList){

        DecimalFormat df = new DecimalFormat("#########.##");
        for(int i=0;i<dataList.size();i++){
            JSONObject jsonObject = dataList.getJSONObject(i);
            String orderCode = jsonObject.getString("orderid");//订单号
            String payTime = jsonObject.getString("paytime");//支付时间
            String orderSubmitTime = jsonObject.getString("paytime");//下单时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            long lt = new Long(orderSubmitTime);
            Date date = new Date(lt);
            orderSubmitTime = simpleDateFormat.format(date);
            String orderLineStatusDesc = jsonObject.getString("status");//订单状态
            String productName = jsonObject.getString("smstitle");//商品名称
            String payAmount = jsonObject.getString("payprice");//实付金额b
            String sid = jsonObject.getString("sid");//子推广账号ID(sid)
            String prePayCommission = jsonObject.getString("profit");//预估佣金
            UserInfo userInfo=userRepository.getUserByRelationId(sid);
            //查询订单是否已经存在
            PublisherOrderDtoBean publisherOrderDtoBean;
            try {
                publisherOrderDtoBean = orderRepository.findByRelationIdCount(orderCode);
            } catch (Exception e) {
                //当发现有多个订单时 删除重复的订单
                List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(orderCode);
                for (int j = 1; j < publisherOrderDtoBeans.size(); j++) {
                    orderJpaRepository.deleteById(publisherOrderDtoBeans.get(j).getId());
                }
                publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
            }
            if (publisherOrderDtoBean == null) {
                PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                o.setFromInfo("mt");
                o.setIsJifen(0);
                o.setIsGif(0);
                //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                o.setBalance(0);
                if(userInfo!=null){
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                }
                o.setAdzone_id(109264550298L);
                o.setAdzone_name(Config.BASE_NAME);
                o.setOrder_type("美团");
                o.setItem_num(1);
                //商品图片
                o.setItem_img("//img2.baidu.com/it/u=1090601754,501627479&fm=26&fmt=auto&gp=0.jpg");
                //商品标题
                o.setItem_title(productName);
                //订单编号
                o.setTrade_id(orderCode);
                o.setTrade_parent_id(orderCode);
                //商品id
                o.setItem_id("0");
                //单个商品金额
                o.setItem_price(df.format(Float.parseFloat(payAmount)));
                float d = Float.parseFloat(prePayCommission);
                //设置佣金金额
                o.setPub_share_pre_fee(prePayCommission);
                //实际支付金额
                o.setAlipay_total_price(payAmount);
                try {
                    //订单支付时间
                    o.setTb_paid_time(sdf.format(sdf.parse(sdf.format(Long.parseLong(payTime) * 1000))));
                    //订单支付时间
                    o.setTk_paid_time(sdf.format(sdf.parse(sdf.format(Long.parseLong(payTime) * 1000))));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //处理订单状态
                o.setTk_status(12);//处理已付款状态
                //新人首次下单 检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                newsUserDownOrder(o, userInfo, d, df);
            } else {
                if(!publisherOrderDtoBean.getPub_share_pre_fee().equals(prePayCommission) && userInfo!=null){
                    publisherOrderDtoBean.setPub_share_pre_fee(prePayCommission);
                    getRate(publisherOrderDtoBean,userInfo, Float.parseFloat(prePayCommission),df,null);
                }
                //处理订单状态 这里处理已付款状态
                setMTStatus(orderLineStatusDesc, publisherOrderDtoBean, userInfo);
            }
        }
    }







    public static String genSign(Map<String,String> map,String[] array,String SECRET) {
        Arrays.sort(array);
        StringBuilder sb=new StringBuilder(SECRET);
        for(String str:array){
            sb.append(str).append(map.get(str));
        }
        sb.append(SECRET);
        return md5(sb.toString());
    }

    public static String md5(String source) {
        String md5Result = null;
        try {
            byte[] hash = org.apache.commons.codec.binary.StringUtils.getBytesUtf8(source);
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(hash);
            hash = messageDigest.digest();
            md5Result = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return md5Result;
    }


    /**
     * 保存京东订单
     *
     * @param jdOrder
     */
    private void saveJdOrder(OrderResp jdOrder) {
        if (jdOrder != null && jdOrder.getSkuList().length > 0 && jdOrder.getOrderId() != null) {
            SkuInfo skuInfo = jdOrder.getSkuList()[0];
            DecimalFormat df = new DecimalFormat("#########.##");
            //通过京东pid获取用户
            UserInfo userInfo = userRepository.getUserByJd(String.valueOf(skuInfo.getPositionId()));
            if (userInfo != null) {
                //查询订单是否已经存在
                PublisherOrderDtoBean publisherOrderDtoBean;
                try {
                    publisherOrderDtoBean = orderRepository.findByRelationIdCount(String.valueOf(jdOrder.getOrderId()));
                } catch (Exception e) {
                    //当发现有多个订单时 删除重复的订单
                    List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(String.valueOf(jdOrder.getOrderId()));
                    for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
                        orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
                    }
                    publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
                }
                if (publisherOrderDtoBean == null) {
                    PublisherOrderDtoBean o = new PublisherOrderDtoBean();
                    o.setFromInfo("jd");
                    o.setIsJifen(0);
                    o.setIsGif(0);
                    //设置为未结算（咱们平台的结算状态 0为没有结算 1为结算）
                    o.setBalance(0);
                    o.setRelation_id(Long.valueOf(userInfo.getRelationId()));
                    o.setInvitation(userInfo.getInvitation());
                    o.setAdzone_id(109264550298L);
                    o.setAdzone_name(Config.BASE_NAME);
                    o.setOrder_type("京东");
                    CommonInfo one = commonRepository.findOne(19);
                    //商品图片
                    o.setItem_img(one.getValue().split(":")[1]+"/logo.png");
                    //商品标题
                    o.setItem_title(skuInfo.getSkuName());
                    //订单编号
                    o.setTrade_id(String.valueOf(jdOrder.getOrderId()));
                    o.setTrade_parent_id(String.valueOf(jdOrder.getOrderId()));
                    //商品id
                    o.setItem_id(String.valueOf(skuInfo.getSkuId()));
                    //单个商品金额
                    o.setItem_price(String.valueOf(skuInfo.getEstimateCosPrice()));
                    //设置佣金金额
                    o.setPub_share_pre_fee(String.valueOf(skuInfo.getEstimateFee()));
                    //实际支付金额
                    o.setAlipay_total_price(String.valueOf(skuInfo.getEstimateCosPrice()));
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                    //订单支付时间
                    o.setTb_paid_time(sdf.format(new Date(jdOrder.getOrderTime())));
                    //订单支付时间
                    o.setTk_paid_time(sdf.format(new Date(jdOrder.getOrderTime())));
                    //获取佣金
                    float d = Float.parseFloat(df.format(Float.parseFloat(String.valueOf(skuInfo.getEstimateFee()))));
                    o.setTk_status(12);//处理已付款状态
                    //统一处理新人免单
                    newsUserDownOrder(o, userInfo, d, df);
                } else {
                    //处理订单状态 这里处理已付款状态
                    setJdStatus(jdOrder, publisherOrderDtoBean, userInfo);
                }
            }

        }

    }


    /**
     * 处理新人首单问题
     *
     * @param o
     * @param userInfo
     * @param money
     * @param df
     */
    private void newsUserDownOrder(PublisherOrderDtoBean o, UserInfo userInfo, float money, DecimalFormat df) {
        PublisherOrderDtoBean publisherOrderDtoBean;
        try {
            publisherOrderDtoBean = orderRepository.findByRelationIdCount(o.getTrade_id());
        } catch (Exception e) {
            //当发现有多个订单时 删除重复的订单
            List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(o.getTrade_id());
            for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
                orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
            }
            publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
        }
        CommonInfo one = commonRepository.findOne(91);
        if ("1".equals(one.getValue())) {
            if (publisherOrderDtoBean != null) {

                o.setRelation_id(publisherOrderDtoBean.getRelation_id());
                o.setFromInfo(publisherOrderDtoBean.getFromInfo());
                o.setId(publisherOrderDtoBean.getId());
                o.setIsGif(publisherOrderDtoBean.getIsGif());
                o.setIsJifen(publisherOrderDtoBean.getIsJifen());
                o.setBalance(publisherOrderDtoBean.getBalance());
                o.setInvitation(publisherOrderDtoBean.getInvitation());
                o.setUserName(publisherOrderDtoBean.getUserName());
                o.setPhone(publisherOrderDtoBean.getPhone());
                o.setInvitationName(publisherOrderDtoBean.getInvitationName());
                o.setInvitationPhone(publisherOrderDtoBean.getInvitationPhone());

                o.setInvitationMoney(publisherOrderDtoBean.getInvitationMoney());
                o.setPub_share_pre_fee_user(publisherOrderDtoBean.getPub_share_pre_fee_user());

                getRate(o, userInfo, money, df, 1);
            } else {
                if (userInfo == null) {
                    o.setPub_share_pre_fee_user(df.format(money));
                    o.setPub_share_pre_fee(df.format(money));
                    getRate(o, userInfo, money, df, 1);
                } else {
                    getRate(o,userInfo,money,df,1);
                }
            }
        } else {
            if (publisherOrderDtoBean != null) {
                o.setRelation_id(publisherOrderDtoBean.getRelation_id());
                o.setFromInfo(publisherOrderDtoBean.getFromInfo());
                o.setId(publisherOrderDtoBean.getId());
                o.setIsGif(publisherOrderDtoBean.getIsGif());
                o.setIsJifen(publisherOrderDtoBean.getIsJifen());
                o.setBalance(publisherOrderDtoBean.getBalance());
                //设置用户本身信息
                o.setPub_share_pre_fee_user(publisherOrderDtoBean.getPub_share_pre_fee_user());
                o.setUserName(publisherOrderDtoBean.getUserName());
                o.setPhone(publisherOrderDtoBean.getPhone());
                //设置直属信息
                o.setInvitationMoney(publisherOrderDtoBean.getInvitationMoney());
                o.setInvitation(publisherOrderDtoBean.getInvitation());
                o.setInvitationName(publisherOrderDtoBean.getInvitationName());
                o.setInvitationPhone(publisherOrderDtoBean.getInvitationPhone());
                //设置非直属信息
                o.setInvitations(publisherOrderDtoBean.getInvitations());
                o.setInvitationMoneys(publisherOrderDtoBean.getInvitationMoneys());
                o.setInvitationNames(publisherOrderDtoBean.getInvitationNames());
                o.setInvitationPhones(publisherOrderDtoBean.getInvitationPhones());
                getRate(o,userInfo,money,df,1);
            } else {
                getRate(o,userInfo,money,df,1);
            }
        }
    }
//    private void newsUserDownOrder(PublisherOrderDtoBean o, UserInfo userInfo, float money, DecimalFormat df) {
//        PublisherOrderDtoBean publisherOrderDtoBean;
//        try {
//            publisherOrderDtoBean = orderRepository.findByRelationIdCount(o.getTrade_id());
//        } catch (Exception e) {
//            //当发现有多个订单时 删除重复的订单
//            List<PublisherOrderDtoBean> publisherOrderDtoBeans = orderRepository.findByRelationIdCountList(o.getTrade_id());
//            for (int i = 1; i < publisherOrderDtoBeans.size(); i++) {
//                orderJpaRepository.deleteById(publisherOrderDtoBeans.get(i).getId());
//            }
//            publisherOrderDtoBean = publisherOrderDtoBeans.get(0);
//        }
//        CommonInfo one = commonRepository.findOne(91);
//        if ("1".equals(one.getValue())) {
//            if (publisherOrderDtoBean != null) {
//
//
//                o.setRelation_id(publisherOrderDtoBean.getRelation_id());
//                o.setFromInfo(publisherOrderDtoBean.getFromInfo());
//                o.setId(publisherOrderDtoBean.getId());
//                o.setIsGif(publisherOrderDtoBean.getIsGif());
//                o.setIsJifen(publisherOrderDtoBean.getIsJifen());
//                o.setBalance(publisherOrderDtoBean.getBalance());
//                o.setInvitation(publisherOrderDtoBean.getInvitation());
//                o.setUserName(publisherOrderDtoBean.getUserName());
//                o.setPhone(publisherOrderDtoBean.getPhone());
//                o.setInvitationName(publisherOrderDtoBean.getInvitationName());
//                o.setInvitationPhone(publisherOrderDtoBean.getInvitationPhone());
//
//                o.setInvitationMoney(publisherOrderDtoBean.getInvitationMoney());
//                o.setPub_share_pre_fee_user(publisherOrderDtoBean.getPub_share_pre_fee_user());
//                orderJpaRepository.save(o);
//            } else {
//                if (userInfo == null) {
//                    o.setPub_share_pre_fee_user(df.format(money));
//                    o.setPub_share_pre_fee(df.format(money));
//                    orderJpaRepository.save(o);
//                } else {
//                    getRate(o,userInfo,money,df,1);
//                }
//            }
//        } else {
//            if (publisherOrderDtoBean != null) {
//                o.setRelation_id(publisherOrderDtoBean.getRelation_id());
//                o.setFromInfo(publisherOrderDtoBean.getFromInfo());
//                o.setId(publisherOrderDtoBean.getId());
//                o.setIsGif(publisherOrderDtoBean.getIsGif());
//                o.setIsJifen(publisherOrderDtoBean.getIsJifen());
//                o.setBalance(publisherOrderDtoBean.getBalance());
//                //设置用户本身信息
//                o.setPub_share_pre_fee_user(publisherOrderDtoBean.getPub_share_pre_fee_user());
//                o.setUserName(publisherOrderDtoBean.getUserName());
//                o.setPhone(publisherOrderDtoBean.getPhone());
//                //设置直属信息
//                o.setInvitationMoney(publisherOrderDtoBean.getInvitationMoney());
//                o.setInvitation(publisherOrderDtoBean.getInvitation());
//                o.setInvitationName(publisherOrderDtoBean.getInvitationName());
//                o.setInvitationPhone(publisherOrderDtoBean.getInvitationPhone());
//                //设置非直属信息
//                o.setInvitations(publisherOrderDtoBean.getInvitations());
//                o.setInvitationMoneys(publisherOrderDtoBean.getInvitationMoneys());
//                o.setInvitationNames(publisherOrderDtoBean.getInvitationNames());
//                o.setInvitationPhones(publisherOrderDtoBean.getInvitationPhones());
//                orderJpaRepository.save(o);
//            } else {
//                if (userInfo == null) {
//                    o.setPub_share_pre_fee_user(df.format(money));
//                    o.setPub_share_pre_fee(df.format(money));
//                    orderJpaRepository.save(o);
//                } else {
//                    getRate(o,userInfo,money,df,1);
//                }
//            }
//        }
//    }



    public PublisherOrderDtoBean getRate(PublisherOrderDtoBean o, UserInfo userInfo, float money, DecimalFormat df,Integer isSend){

        if (userInfo == null) {
            o.setInvitation("0");
            o.setInvitations("0");
            o.setRelation_id(0);

            //顶级没钱
            o.setTopInvitationMoney("0");
            o.setTopRelationId("");
            //直属没钱
            o.setInvitationMoney("0");
            o.setInvitationName("0");
            o.setInvitationPhone("0");
            o.setPub_share_pre_fee_user("0");
            o.setPub_share_pre_fee(df.format(money));
            //非直属没钱
            o.setInvitationMoneys("0");
            return orderJpaRepository.save(o);
        }


        CommonInfo one = commonRepository.findOne(91);
        if("1".equals(one.getValue())){
            BigDecimal moneys = BigDecimal.valueOf(money);
            //计算用户本身佣金
            //计算方式（淘宝总佣金*用户佣金等级）
//            BigDecimal b = moneys.multiply(new BigDecimal(userInfo.getGrade()));

            //设置直属邀请人信息
            o.setInvitation(userInfo.getInvitation());
            o.setUserName(userInfo.getNickName());
            o.setPhone(userInfo.getPhone());

            //获取直属人信息
            BigDecimal rate = Optional.ofNullable(userInfo.getGrade())
                    .map(BigDecimal::new)
                    .orElse(BigDecimal.ZERO);
                BigDecimal commMoneys = moneys.multiply(rate);
            return  doComm1(userInfo, commMoneys, o,df,isSend);
        }else{
            //计算用户本身佣金
            //计算方式（淘宝总佣金*用户佣金等级）
            BigDecimal moneys = BigDecimal.valueOf(money);


            //设置用户自身信息
            o.setUserName(userInfo.getNickName());
            o.setPhone(userInfo.getPhone());
            //设置直属成员信息
//            o.setInvitation(userInfo.getInvitation());
            o.setInvitation(userInfo.getRelationId());
            //获取直属人信息
            BigDecimal rate = Optional.ofNullable(userInfo.getGrade())
                    .map(BigDecimal::new)
                    .orElse(BigDecimal.ZERO);
            BigDecimal commMoneys = moneys.multiply(rate);
           return doComm2(userInfo, commMoneys, o, df,isSend);
            }
    }
    //获取顶级邀请人
    UserInfo getTopRelationUser(UserInfo userByRelationId ){
        String invitation = userByRelationId.getInvitation();

        if (StringUtils.isBlank(invitation)) {
            if (userByRelationId.getIsTopTuan() == 1) {
                return userByRelationId;
            }else {
                return null;
            }
        }
        UserInfo next = userRepository.getUserByRelationId(invitation);
        if (next == null) {
            if (userByRelationId.getIsTopTuan() == 1) {
                return userByRelationId;
            }else {
                return null;
            }
        }
        return getTopRelationUser(next);
    }

    //处理一级分佣
    PublisherOrderDtoBean doComm1(UserInfo directInviteUser,BigDecimal comm,PublisherOrderDtoBean o,DecimalFormat df,Integer isSend){
        UserInfo topRelationUser = getTopRelationUser(directInviteUser);

        CommonInfo topInviteRate = commonRepository.findOne(264);
        BigDecimal topRate = Optional.ofNullable(topInviteRate.getValue())
                .map(item->{
                    if (topRelationUser == null) {
                        return BigDecimal.ZERO;
                    }else {
                        return new BigDecimal(item);
                    }
                })
                .orElse(BigDecimal.ZERO);
        BigDecimal zhiRate = Optional.ofNullable(directInviteUser.getZhiRate())
                .map(BigDecimal::new)
                .orElse(BigDecimal.ZERO);

        if (topRate.add(zhiRate).doubleValue() > 1d) {
                zhiRate = BigDecimal.ONE.subtract(topRate);
        }



        //顶级团长的佣金
        BigDecimal topInviteComm = comm.multiply(topRate);
        //直属团长的佣金
        BigDecimal directInviteComm = comm.multiply(zhiRate);

        //顶级
        if (topRelationUser != null) {
            o.setTopInvitationMoney(df.format(topInviteComm));
            o.setTopRelationId(topRelationUser.getRelationId());
        }
        //直属
        o.setInvitationMoney(df.format(directInviteComm));
        o.setInvitationName(directInviteUser.getNickName());
        o.setInvitationPhone(directInviteUser.getPhone());

        o.setPub_share_pre_fee_user(df.format("0"));

        //非直属没钱
        o.setInvitationMoneys(df.format(BigDecimal.ZERO));

        //推送直属信息
        if (directInviteComm.doubleValue() > 0.00 && isSend!=null) {
            twoUserMessages(directInviteUser.getOpenId(), directInviteUser.getId(), directInviteUser.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
        }

        o.setInvitation(directInviteUser.getRelationId());
        o.setInvitations("0");
        o.setRelation_id(Long.parseLong(directInviteUser.getRelationId()));
        return orderJpaRepository.save(o);
    }
    //处理二级分佣
    PublisherOrderDtoBean doComm2(UserInfo directInviteUser,BigDecimal comm,PublisherOrderDtoBean o,DecimalFormat df,Integer isSend){
        UserInfo topRelationUser = getTopRelationUser(directInviteUser);
        CommonInfo topInviteRate = commonRepository.findOne(264);

        BigDecimal topRate = Optional.ofNullable(topInviteRate.getValue())
                .map(item->{
                    if (topRelationUser == null) {
                        return BigDecimal.ZERO;
                    }else {
                        return new BigDecimal(item);
                    }
                })
                .orElse(BigDecimal.ZERO);
        BigDecimal zhiRate = Optional.ofNullable(directInviteUser.getZhiRate())
                .map(BigDecimal::new)
                .orElse(BigDecimal.ZERO);
        BigDecimal feiRate = Optional.ofNullable(directInviteUser.getFeiRate())
                .map(BigDecimal::new)
                .orElse(BigDecimal.ZERO);

        if (topRate.add(zhiRate).add(feiRate).doubleValue() > 1d) {
            if(topRate.add(zhiRate).doubleValue()>1d){
                zhiRate = BigDecimal.ONE.subtract(topRate);
                feiRate = BigDecimal.ZERO;
            } else {
                feiRate = BigDecimal.ONE.subtract(topRate).min(zhiRate);
            }

        }


        UserInfo nonDirectInviteUser = userRepository.getUserByRelationId(directInviteUser.getInvitation());

        //顶级团长的佣金
            BigDecimal topInviteComm = comm.multiply(topRate);
            //直属团长的佣金
            BigDecimal directInviteComm = comm.multiply(zhiRate);
            //非直属团长的佣金
            BigDecimal nonDirectInviteComm = comm.multiply(feiRate);

            //顶级
            o.setTopInvitationMoney(df.format(topInviteComm));
        if (topRelationUser != null) {
            o.setTopRelationId(topRelationUser.getRelationId());
        }
            //直属
            o.setInvitationMoney(df.format(directInviteComm));
            o.setInvitationName(directInviteUser.getNickName());
            o.setInvitationPhone(directInviteUser.getPhone());
            //非直属
            o.setInvitationMoneys(df.format(nonDirectInviteComm));

        //推送直属信息
        if (directInviteComm.doubleValue() > 0.00 && isSend!=null) {
            twoUserMessages(directInviteUser.getOpenId(), directInviteUser.getId(), directInviteUser.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
        }
        //推送非直属信息
        if (nonDirectInviteUser!=null&&nonDirectInviteComm.doubleValue() > 0.00 && isSend!=null) {
            twoUserMessages(nonDirectInviteUser.getOpenId(), nonDirectInviteUser.getId(), nonDirectInviteUser.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
        }

        o.setInvitation(directInviteUser.getRelationId());
        if (nonDirectInviteUser != null) {
            o.setInvitations(nonDirectInviteUser.getRelationId());
        }
        o.setRelation_id(Long.parseLong(directInviteUser.getRelationId()));
        return orderJpaRepository.save(o);
    }
//    public PublisherOrderDtoBean getRate(PublisherOrderDtoBean o, UserInfo userInfo, float money, DecimalFormat df,Integer isSend){
//        CommonInfo one = commonRepository.findOne(91);
//        if("1".equals(one.getValue())){
//            BigDecimal moneys = BigDecimal.valueOf(money);
//            //计算用户本身佣金
//            //计算方式（淘宝总佣金*用户佣金等级）
//            BigDecimal b = moneys.multiply(new BigDecimal(userInfo.getGrade()));
//
//            //设置直属邀请人信息
//            o.setInvitation(userInfo.getInvitation());
//            o.setUserName(userInfo.getNickName());
//            o.setPhone(userInfo.getPhone());
//
//            //获取直属人信息
//            UserInfo userByRelationId = userRepository.getUserByRelationId(userInfo.getInvitation());
//            if (userByRelationId != null) {
//                //设置直属人信息
//                //淘宝总佣金*直属佣金比例
//                BigDecimal f1 = moneys.multiply(new BigDecimal(userByRelationId.getZhiRate()));
//                o.setInvitationMoney(df.format(f1));
//                o.setInvitationName(userByRelationId.getNickName());
//                o.setInvitationPhone(userByRelationId.getPhone());
//                //推送直属信息
//                if (f1.doubleValue() > 0.00 && isSend!=null) {
//                    twoUserMessages(userByRelationId.getOpenId(), userByRelationId.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
//                }
//            }
//            //设置用户自身佣金
//            o.setPub_share_pre_fee_user(df.format(b));
//            String mian = commonRepository.findOne(54).getValue();
//
//            //处理校验免单业务
////            if (mian.equals("是")) {
////                //检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
////                if (Integer.parseInt(orderRepository.isNewsUser(o.getRelation_id())) == 0) {
////                    //设置当前是免单商品
////                    o.setIsGif(1);
////                    //支付金额大于5元自动提现结算到用户提现中（前端限制了 用户必须够十元才可以提现的）
////                    float f = Float.parseFloat(o.getAlipay_total_price());
////                    //支付金额大于5元只给用户返5元
////                    if (f > 5) {
////                        //收入用户首单大于5元 直接返佣金金额
////                        if (b.doubleValue() < 5) {
////                            o.setPub_share_pre_fee_user("5");
////                        }
////                    } else {
////                        //小于5元全额返回
////                        o.setPub_share_pre_fee_user(o.getAlipay_total_price());
////                    }
////                }
////            }
//
//            //用户本身推送消息
//            PublisherOrderDtoBean save = orderJpaRepository.save(o);
//            if(b.doubleValue()>0.00 && isSend!=null){
//                bindRelationSucces(userInfo.getOpenId(), userInfo.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getPub_share_pre_fee_user(), o.getItem_title());
//            }
//            return save;
//        }else{
//            //计算用户本身佣金
//            //计算方式（淘宝总佣金*用户佣金等级）
//            BigDecimal moneys = BigDecimal.valueOf(money);
//            //计算用户本身佣金
//            //计算方式（淘宝总佣金*用户佣金等级）
//            BigDecimal b = moneys.multiply(new BigDecimal(userInfo.getGrade()));
//
//
//            //设置用户自身信息
//            o.setUserName(userInfo.getNickName());
//            o.setPhone(userInfo.getPhone());
//            //设置直属成员信息
//            o.setInvitation(userInfo.getInvitation());
//
//            //获取直属人信息
//            UserInfo userByRelationId = userRepository.getUserByRelationId(userInfo.getInvitation());
//            if (userByRelationId != null) {
//                //设置直属人信息
//                //淘宝总佣金*直属佣金比例
//                BigDecimal f1 = moneys.multiply(new BigDecimal(userByRelationId.getZhiRate()));
//                o.setInvitationMoney(df.format(f1));
//                o.setInvitationName(userByRelationId.getNickName());
//                o.setInvitationPhone(userByRelationId.getPhone());
//                //推送直属信息
//                if (f1.doubleValue() > 0.00 && isSend!=null) {
//                    twoUserMessages(userByRelationId.getOpenId(), userByRelationId.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
//                }
//
//                //获取非直属人信息
//                UserInfo userByRelationIds = userRepository.getUserByRelationId(userByRelationId.getInvitation());
//                if (userByRelationIds != null) {
//                    //设置非直属人信息
//                    //淘宝总佣金*非直属佣金比例
//                    BigDecimal f2 = moneys.multiply(new BigDecimal(userByRelationIds.getFeiRate()));
//                    o.setInvitations(userByRelationId.getInvitation());
//                    o.setInvitationMoneys(df.format(f2));
//                    o.setInvitationNames(userByRelationIds.getNickName());
//                    o.setInvitationPhones(userByRelationIds.getPhone());
//                    if (f2.doubleValue() > 0.00 && isSend!=null) {
//                        threeUserMessage(userByRelationIds.getOpenId(), userByRelationIds.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoneys(), o.getItem_title());
//                    }
//                }
//            }
//            //用户佣金=淘宝总佣金*用户佣金等级
//            //存储用户佣金
//            o.setPub_share_pre_fee_user(df.format(b));
//            //检测免单
////            String mian = commonRepository.findOne(54).getValue();
////            if (mian.equals("是")) {
////                //检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
////                if (Integer.parseInt(orderRepository.isNewsUser(o.getRelation_id())) == 0) {
////                    //设置当前是免单商品
////                    o.setIsGif(1);
////                    //支付金额大于5元自动提现结算到用户提现中（前端限制了 用户必须够十元才可以提现的）
////                    float f = Float.parseFloat(o.getAlipay_total_price());
////                    //支付金额大于5元只给用户返5元
////                    if (f > 5) {
////                        //收入用户首单大于5元 直接返佣金金额
////                        if (b.doubleValue() < 5) {
////                            o.setPub_share_pre_fee_user("5");
////                        }
////                    } else {
////                        //小于5元全额返回
////                        o.setPub_share_pre_fee_user(o.getAlipay_total_price());
////                    }
////                }
////            }
//            PublisherOrderDtoBean save = orderJpaRepository.save(o);
//            if(b.doubleValue()>0.00 && isSend!=null){
//                bindRelationSucces(userInfo.getOpenId(), userInfo.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getPub_share_pre_fee_user(), o.getItem_title());
//            }
//            return save;
//        }
//    }

    public void bindingOrder(PublisherOrderDtoBean o, UserInfo userInfo, String moneyss) {
        CommonInfo one = commonRepository.findOne(91);
        if ("1".equals(one.getValue())) {
            DecimalFormat df = new DecimalFormat("#########.##");
            Float money = Float.parseFloat(moneyss);
            BigDecimal moneys = BigDecimal.valueOf(money);
            //计算用户本身佣金
            //计算方式（淘宝总佣金*用户佣金等级）
            BigDecimal b = moneys.multiply(new BigDecimal(userInfo.getGrade()));

            //设置直属邀请人信息
            o.setInvitation(userInfo.getInvitation());
            o.setUserName(userInfo.getNickName());
            o.setPhone(userInfo.getPhone());

            //获取直属人信息
            UserInfo userByRelationId = userRepository.getUserByRelationId(userInfo.getInvitation());
            if (userByRelationId != null) {
                //设置直属人信息
                //淘宝总佣金*直属佣金比例
                BigDecimal f1 = moneys.multiply(new BigDecimal(userByRelationId.getZhiRate()));
                o.setInvitationMoney(df.format(f1));
                o.setInvitationName(userByRelationId.getNickName());
                o.setInvitationPhone(userByRelationId.getPhone());
                //推送直属信息
                if (f1.doubleValue() > 0.00) {
                    twoUserMessages(userByRelationId.getOpenId(), userByRelationId.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
                }
            }
            //设置用户自身佣金
            o.setPub_share_pre_fee_user(df.format(b));
            String mian = commonRepository.findOne(54).getValue();
            if (mian.equals("是")) {
                //检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                if (Integer.parseInt(orderRepository.isNewsUser(o.getRelation_id())) == 0) {
                    //设置当前是免单商品
                    o.setIsGif(1);
                    //支付金额大于5元自动提现结算到用户提现中（前端限制了 用户必须够十元才可以提现的）
                    float f = Float.parseFloat(o.getAlipay_total_price());
                    //支付金额大于5元只给用户返5元
                    if (f > 5) {
                        //收入用户首单大于5元 直接返佣金金额
                        if (b.doubleValue() < 5) {
                            o.setPub_share_pre_fee_user("5");
                        }
                    } else {
                        //小于5元全额返回
                        o.setPub_share_pre_fee_user(o.getAlipay_total_price());
                    }
                }
            }
            orderJpaRepository.save(o);
            bindRelationSucces(userInfo.getOpenId(), userInfo.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getPub_share_pre_fee_user(), o.getItem_title());
        } else {
            DecimalFormat df = new DecimalFormat("#########.##");
            Float money = Float.parseFloat(moneyss);
            //计算用户本身佣金
            //计算方式（淘宝总佣金*用户佣金等级）
            BigDecimal moneys = BigDecimal.valueOf(money);
            //计算用户本身佣金
            //计算方式（淘宝总佣金*用户佣金等级）
            BigDecimal b = moneys.multiply(new BigDecimal(userInfo.getGrade()));


            //设置用户自身信息
            o.setUserName(userInfo.getNickName());
            o.setPhone(userInfo.getPhone());
            //设置直属成员信息
            o.setInvitation(userInfo.getInvitation());

            //获取直属人信息
            UserInfo userByRelationId = userRepository.getUserByRelationId(userInfo.getInvitation());
            if (userByRelationId != null) {
                //设置直属人信息
                //淘宝总佣金*直属佣金比例
                BigDecimal f1 = moneys.multiply(new BigDecimal(userByRelationId.getZhiRate()));
                o.setInvitationMoney(df.format(f1));
                o.setInvitationName(userByRelationId.getNickName());
                o.setInvitationPhone(userByRelationId.getPhone());
                //推送直属信息
                if (f1.doubleValue() > 0.00) {
                    twoUserMessages(userByRelationId.getOpenId(), userByRelationId.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoney(), o.getItem_title());
                }

                //获取非直属人信息
                UserInfo userByRelationIds = userRepository.getUserByRelationId(userByRelationId.getInvitation());
                if (userByRelationIds != null) {
                    //设置非直属人信息
                    //淘宝总佣金*非直属佣金比例
                    BigDecimal f2 = moneys.multiply(new BigDecimal(userByRelationIds.getFeiRate()));
                    o.setInvitations(userByRelationId.getInvitation());
                    o.setInvitationMoneys(df.format(f2));
                    o.setInvitationNames(userByRelationIds.getNickName());
                    o.setInvitationPhones(userByRelationIds.getPhone());
                    if (f2.doubleValue() > 0.00) {
                        threeUserMessage(userByRelationIds.getOpenId(), userByRelationIds.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getInvitationMoneys(), o.getItem_title());
                    }
                }
            }
            //用户佣金=淘宝总佣金*用户佣金等级
            //存储用户佣金
            o.setPub_share_pre_fee_user(df.format(b));
            String mian = commonRepository.findOne(54).getValue();
            if (mian.equals("是")) {
                //检查是不是新用户（获取用户订单 列表没有订单表示是新用户）
                if (Integer.parseInt(orderRepository.isNewsUser(o.getRelation_id())) == 0) {
                    //设置当前是免单商品
                    o.setIsGif(1);
                    //支付金额大于5元自动提现结算到用户提现中（前端限制了 用户必须够十元才可以提现的）
                    float f = Float.parseFloat(o.getAlipay_total_price());
                    //支付金额大于5元只给用户返5元
                    if (f > 5) {
                        //收入用户首单大于5元 直接返佣金金额
                        if (b.doubleValue() < 5) {
                            o.setPub_share_pre_fee_user("5");
                        }
                    } else {
                        //小于5元全额返回
                        o.setPub_share_pre_fee_user(o.getAlipay_total_price());
                    }
                }
            }
            orderJpaRepository.save(o);
            bindRelationSucces(userInfo.getOpenId(), userInfo.getId(), userInfo.getNickName(), o.getTb_paid_time(), o.getAlipay_total_price(), o.getTrade_id(), o.getPub_share_pre_fee_user(), o.getItem_title());
        }
    }


    /**
     * 优惠券抵扣业务处理
     */
    private void handleCouponOrder(PublisherOrderDtoBean publisherOrderDtoBean,UserInfo userInfo,
                                   String orderChannel,String orderStatus){
        CommonInfo one = commonRepository.findOne(100);
        if(one==null){
//            log.info("handleCouponOrder error");
        }
        if(publisherOrderDtoBean.getRelation_id()!=0L){
            if("是".equals(one.getValue())){
//                log.info("==userInfo.getRelationId======"+userInfo.getRelationId());
                Boolean aBoolean = couponOrderDetailService.saveTaobaoCouponOrderDetail(String.valueOf(userInfo.getRelationId()),
                        publisherOrderDtoBean.getTrade_id(), String.valueOf(publisherOrderDtoBean.getItem_id()),
                        orderChannel,orderStatus,publisherOrderDtoBean.getItem_title());
                if(aBoolean==Boolean.FALSE){
//                    log.info("handleCouponOrder error 2");
                }
            }
        }
    }

    /**
     * 多麦商品更新状态 -1 无效 0 未确认 1 确认 2 结算
     *
     * @param
     */
    private void setDMStatus(String status, PublisherOrderDtoBean o) {
        if ("-1".equals(status)) {
            o.setTk_status(13);
        }else if("2".equals(status)){
            o.setTk_status(3);
        }
        orderJpaRepository.save(o);
    }

    /**
     * 聚推客商品更新状态 订单统一状态，0：未付款 1：已付款 2：待结算 3：已结算 4：无效订单
     *
     * @param
     */
    private void setJTKStatus(String status, PublisherOrderDtoBean o) {
        if ("4".equals(status)) {
            o.setTk_status(13);
        }else if("3".equals(status)){
            o.setTk_status(3);
        }
        orderJpaRepository.save(o);
    }

    /**
     * 抖音商品更新状态 1已付款、2已结算、3已退款
     *
     * @param
     */
    private void setDouYinStatus(String status, PublisherOrderDtoBean o) {
        if ("1".equals(status)) {
            o.setTk_status(12);
        }else if("2".equals(status)){
            o.setTk_status(3);
        }else if("3".equals(status)){
            o.setTk_status(13);
        }
        orderJpaRepository.save(o);
    }

    /**
     * 唯品会商品更新状态 已下单、已付款、已签收、待结算、已结算、已失效
     *
     * @param
     */
    private void setWPHStatus(String status, PublisherOrderDtoBean o) {
        if ("已失效".equals(status)) {
            o.setTk_status(13);
        }else if("已结算".equals(status)){
            o.setTk_status(3);
        }
        orderJpaRepository.save(o);
    }


    /**
     * 美团商品更新状态
     *
     * @param
     */
    private void setMTStatus(String status, PublisherOrderDtoBean o, UserInfo userInfo) {
        if ("1".equals(status)) {
            o.setTk_status(12);
        }else if("8".equals(status)){
            o.setTk_status(3);
        }else if("9".equals(status)){
            o.setTk_status(13);
        }
        orderJpaRepository.save(o);
    }

    /**
     * 计算结算用户订单业务处理
     *
     * @param o
     * @param df
     */
    private void setUserOrderJiFen(PublisherOrderDtoBean o, DecimalFormat df, UserInfo userInfo) {
        //校验当前订单是否已经积分过 0表示未积分 1表示已积分
        if (o.getIsJifen() == 0) {
            //如果用户现在的积分不等于空计算用户现有订单积分
            if (userInfo.getOrderJifen() != null) {
                //订单支付积分
                float d1 = Float.parseFloat(o.getAlipay_total_price());
                //用户已经有的积分
                float a = Float.parseFloat(userInfo.getOrderJifen());
                //计算现有积分和获得的积分结算
                userInfo.setOrderJifen(df.format(a + d1));
            } else {
                userInfo.setOrderJifen(o.getAlipay_total_price());
            }
            //保存积分明细
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            JiFen jiFen = new JiFen();
            jiFen.setCreateAt(sdf.format(now));
            jiFen.setContent(o.getItem_title());
            jiFen.setDes(o.getItem_title());
            jiFen.setNumber(o.getAlipay_total_price());
            jiFen.setUserId(String.valueOf(userInfo.getId()));
            jiFenRepository.save(jiFen);
            //设置订单已经计算积分
            o.setIsJifen(1);
        }
        //校验是不是新人首单订单
        if (o.getIsGif() == 1) {
            //新人首单结算自动提现
            float f = Float.parseFloat(o.getPub_share_pre_fee_user());
            float g = Float.parseFloat(userInfo.getJifen());
            userInfo.setJifen(df.format(g + f));
            //设置平台订单结算状态
            o.setBalance(1);
            //设置免单结算
            o.setIsGif(2);
        }
        userJpaRepository.save(userInfo);
        orderJpaRepository.save(o);
    }

    /**
     * 京东商品更新状态
     *
     * @param jdOrder
     */
    private void setJdStatus(OrderResp jdOrder, PublisherOrderDtoBean o, UserInfo userInfo) {
        SkuInfo skuInfo = jdOrder.getSkuList()[0];
        DecimalFormat df = new DecimalFormat("#########.##");
        if (skuInfo.getValidCode() == 16) {
            o.setTk_status(12);//处理已付款状态
            orderJpaRepository.save(o);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"JD","12");
        }
        if (skuInfo.getValidCode() != 18 && skuInfo.getValidCode() != 17 && skuInfo.getValidCode() != 16) {
            o.setTk_status(13); //已失效
            orderJpaRepository.save(o);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"JD","13");
        }
        if (skuInfo.getValidCode() == 18 || skuInfo.getValidCode() == 17) {
            o.setTk_status(3); //已经结算
            //统一处理用户订单积分
            setUserOrderJiFen(o, df, userInfo);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"JD","3");
        }
    }

    /**
     * 处理拼多多订单更新状态
     *
     * @param pddOrder
     */
    private void setStatus(PddOrder pddOrder, PublisherOrderDtoBean o, UserInfo userInfo) {
        DecimalFormat df = new DecimalFormat("#########.##");
        if (pddOrder.getOrder_status() == 0 || pddOrder.getOrder_status() == 1) {
            o.setTk_status(12);//处理已付款状态
            orderJpaRepository.save(o);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"PDD","12");
        }
        if (pddOrder.getOrder_status() == 4 || pddOrder.getOrder_status() == 8) {
            o.setTk_status(13); //已失效
            orderJpaRepository.save(o);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"PDD","13");
        }
        if (pddOrder.getOrder_status() == 3 || pddOrder.getOrder_status() == 2 || pddOrder.getOrder_status() == 5) {
            o.setTk_status(3); //已经结算
            //统一处理用户订单积分
            setUserOrderJiFen(o, df, userInfo);
            //处理卡券抵扣业务
            handleCouponOrder(o,userInfo,"PDD","3");
        }
    }



    /**
     * 新订单
     */
    private void twoUserMessages(String openId, long id, String nickName, String downTime, String money, String orderId, String yongjing, String name) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(4));
        messageInfo.setContent("收到一个二级佣金新订单【" + name + "】，获得【" + yongjing + "元佣金】");
        messageInfo.setTitle("二级佣金新订单通知");
        messageInfo.setUserName("成员：" + nickName);
        messageInfo.setUserId(String.valueOf(id));
        UserInfo userInfo = userJpaRepository.findById(id).orElse(null);
        if (userInfo != null && userInfo.getClientid() != null) {
            userService.pushToSingle("二级佣金新订单通知", "收到一个二级佣金新订单【" + name + "】，获得【" + yongjing + "元佣金】", userInfo.getClientid());
        }
        iMessageService.saveBody(messageInfo);
        CommonInfo three = commonRepository.findOne(35);
        String apkey = Config.orderNotification;
        if (three != null) {
            apkey = three.getValue();
        }

        //后台服务域名配置
        CommonInfo url = commonRepository.findOne(19);
        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
        data.put("thing4", new TemplateMessageItem("收到一个二级佣金新订单", "#d71345"));
        data.put("thing3", new TemplateMessageItem("获得" + yongjing + "元佣金", "#d71345"));
        accountService.sendWxMessage(apkey, data, openId, url.getValue() + "/pages/member/user");
    }

    /**
     * 新订单
     */
    private void threeUserMessage(String openId, long id, String nickName, String downTime, String money, String orderId, String yongjing, String name) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(4));
        messageInfo.setContent("收到一个三级佣金新订单【" + name + "】，获得【" + yongjing + "元佣金】");
        messageInfo.setTitle("三级佣金新订单通知");
        messageInfo.setUserName("三级成员：" + nickName);
        messageInfo.setUserId(String.valueOf(id));
        UserInfo userInfo = userJpaRepository.findById(id).orElse(null);
        if (userInfo != null && userInfo.getClientid() != null) {
            userService.pushToSingle("三级佣金新订单通知", "收到一个三级佣金新订单【" + name + "】，获得【" + yongjing + "元佣金】", userInfo.getClientid());
        }
        iMessageService.saveBody(messageInfo);
        CommonInfo three = commonRepository.findOne(35);
        String apkey = Config.orderNotification;
        if (three != null) {
            apkey = three.getValue();
        }

        //后台服务域名配置
        CommonInfo url = commonRepository.findOne(19);
        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
        data.put("thing4", new TemplateMessageItem("收到一个三级佣金新订单", "#d71345"));
        data.put("thing3", new TemplateMessageItem("获得"+ yongjing +"元佣金", "#d71345"));
        accountService.sendWxMessage(apkey, data, openId, url.getValue() + "/pages/member/user");
    }


    /**
     * 新订单
     */
    private void bindRelationSucces(String openId, long id, String nickName, String downTime, String money, String orderId, String yongjing, String name) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(4));
        messageInfo.setContent("收到一个新订单【" + name + "】，获得【" + yongjing + "元佣金】");
        messageInfo.setTitle("新订单通知");
        messageInfo.setUserName(nickName);
        messageInfo.setUserId(String.valueOf(id));
        UserInfo userInfo = userJpaRepository.findById(id).orElse(null);
        if (userInfo != null && userInfo.getClientid() != null) {
            userService.pushToSingle("新订单通知", "收到一个新订单【" + name + "】，获得【" + yongjing + "元佣金】", userInfo.getClientid());
        }
        iMessageService.saveBody(messageInfo);
        CommonInfo three = commonRepository.findOne(35);
        String apkey = Config.orderNotification;
        if (three != null) {
            apkey = three.getValue();
        }
        //后台服务域名配置
        CommonInfo url = commonRepository.findOne(19);
        LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
        data.put("thing4", new TemplateMessageItem("收到一个新订单", "#d71345"));
        data.put("thing3", new TemplateMessageItem("获得"+ yongjing +"元佣金", "#d71345"));
        accountService.sendWxMessage(apkey, data, openId, url.getValue() + "/pages/member/user");
    }

}
